package cn.smbms.controller;

import cn.smbms.pojo.PageSupport;
import cn.smbms.pojo.User;
import cn.smbms.service.user.UserService;
import org.apache.log4j.Logger;
import org.aspectj.bridge.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    private Logger logger = Logger.getLogger(UserController.class);
    private ArrayList<User> userList = new ArrayList<User>();
    @Resource
    private UserService userService;

    //示例25
    @RequestMapping(value = "/syserror.html")
    public String syserror(){return "syserror";}

   /* public UserController(){
        try {//初始化用户数据
            userList.add(new User(2,"liming","李明","0000000",2,
                    new SimpleDateFormat("yyyy-MM-dd").parse("1983-12-10"),
                    "13688884457","北京市东城区前门东大街9号",2,new Date(),
                    1,new Date()));
            userList.add(new User(5,"hanlubiao","韩路彪","0000000",2,
                    new SimpleDateFormat("yyyy-MM-dd").parse("1984-06-05"),
                    "18567542321","北京市朝阳区北辰中心12号",2,new Date(),
                    1,new Date()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }*/

    //没有查询条件的情况下，获取userList（公共查询）
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(Model model){
        logger.info("无查询条件下，获取userList（公共查询） ====== userList");
        model.addAttribute("queryUserList",userList);
        return "user/userlist";
    }

    private ArrayList<User> queryUserList = new ArrayList<User>();
    public String list(@RequestParam(value = "userName",required = false)String userName,Model model){
        logger.info("查询条件：userName："+userName + ",获取userList=====");
        if (userName != null && !userName.equals("")){
            for (User user:userList){
                if (user.getUserName().indexOf(userName) != -1){
                    queryUserList.add(user);
                }
            }
            model.addAttribute("queryUserList",queryUserList);
        }else {
            model.addAttribute("queryUserList",userList);
        }
        return "user/userlist";
    }

    //示例17login()方法实现跳转到系统登录页
    @RequestMapping(value = "/login.html")
    public String login(){
        logger.debug("UserController welcome SMBMS============================");
        return "login";
    }


    //示例18  实现登录
    @RequestMapping(value = "/dologin.html",method = RequestMethod.POST)
    public String doLogin(@RequestParam String userCode, @RequestParam String userPassword, HttpSession session, HttpServletRequest request) throws Exception{
        logger.debug("doLogin=======================================================");
        //调用service方法，进行用户匹配
        User user = userService.login(userCode,userPassword);
        if (null != user){//登录成功
            //放入session
            //session.setAttribute(Constants.USER_SESSION,user);
            //页面跳转（frame.jsp）
            return "redirect:/user/main.html";
        }else {
            //页面跳转（login.jsp）
            request.setAttribute("error","用户名或密码不正确");
            return "login";
        }
    }
    @RequestMapping(value = "/main.html")
    public String main(HttpSession session){
        /*if (session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/user/login.html";
        }*/
        return "frame";
    }

    //示例22
    @RequestMapping(value = "exlogin.html",method = RequestMethod.GET)
    public String exLogin(@RequestParam String userCode,@RequestParam String userPassword) throws Exception{
        logger.debug("exLogin===================================");
        //调用service方法，进行用户匹配
        User user = userService.login(userCode,userPassword);
        if (null != user){//登录失败
            throw new RuntimeException("用户名或密码不正确");
        }
        return "redirect:/user/main.html";
    }
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest req){
        req.setAttribute("e",e);
        return "error";
    }
}
